<template>
  <div class="app-container" style="overflow: auto;">
    <div class="top-two-panel">
      <div class="top">
        <el-form :inline="true" :model="dataSource">
          <el-form-item v-if="this.src === 'local'" label="供应商" class="mt-form-item-left">
            <el-select
              v-model="submitParams.left.s_id"
              v-loading="supplierLoading"
              placeholder="请选择供应商"
              size="small"
              @change="handleSupplierChange"
            >
              <el-option v-for="item in dataSource.suppliers" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item v-if="this.src === 'local'" label="目录" class="mt-form-item-center">
            <el-select
              v-model="submitParams.left.c_id"
              v-loading="catalogLoading"
              size="small"
              placeholder="请选择目录"
              multiple
              :disabled="catalogAvailable"
              @change="checkSelections"
            >
              <el-option
                v-for="item in dataSource.catalogs"
                :key="item.id"
                :label="'[' + item.product__count + ']' + item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="站点" class="mt-form-item-right">
            <el-select
              v-model="submitParams.left.w_id"
              v-loading="websiteLoading"
              placeholder="请选择站点"
              size="small"
              clearable
              @change="handleWebsiteChange"
            >
              <el-option v-for="item in dataSource.websites" :key="item.id" :label="item.domain" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item v-if="this.src === 'crawl'" label="目录" class="mt-form-item-right">
            <el-select
              v-model="submitParams.left.crawl_category_name"
              v-loading="crawl_category_loading"
              placeholder="可选择目录"
              size="small"
              filterable
              clearable
            >
              <el-option
                v-for="(item, index) in dataSource.crawl_category_names"
                :key="index"
                :label="'[' + item.product__count + ']' + item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>

        </el-form>

        <el-input
          v-model="submitParams.left.kw"
          :disabled="!searchAvailable"
          size="small"
          placeholder="选择以上选项后，输入内容可进行筛选"
          class="input-with-select"
          @keyup.enter="handleSearch"
        >
          <el-button slot="append" :disabled="!searchAvailable" icon="el-icon-search" @click="handleSearch">搜索
          </el-button>
        </el-input>
      </div>
      <div id="line" />

      <div class="bottom">
        <div v-if="dataSource.productTableData.length" class="btn-group">
          <el-button
            size="mini"
            type="success"
            :disabled="!leftTableCurrentSelection.length"
            @click="showProductEditFieldsDialog(leftTableCurrentSelection, 'multi')"
          >修改选中项产品信息
          </el-button>
          <el-button
            size="mini"
            type="warning"
            :disabled="!leftTableCurrentSelection.length"
            @click="handleEditProductAttr(leftTableCurrentSelection)"
          >修改选中项模版属性
          </el-button>
          <el-dropdown
            split-button
            type="primary"
            size="mini"
            trigger="click"
            @click.stop="addSelection"
          >
            添加选中项
            <el-dropdown-menu slot="dropdown">
              <!--<el-dropdown-item @click.native.stop="addTotal">添加全部({{total}})个产品-->
              <!--</el-dropdown-item>-->
            </el-dropdown-menu>
          </el-dropdown>

          <el-button size="mini" @click="clearSelection">取消选中</el-button>
          <el-button
            v-if="src === 'crawl'"
            type="danger"
            size="mini"
            @click="handleDeleteProduct('')"
          >删除全部{{ total }}</el-button>
        </div>
        <span class="mt-span">待选产品</span>

        <el-table
          ref="leftTable"
          v-loading.body="productTableLoading"
          size="mini"
          :data="dataSource.productTableData"
          border
          fit
          highlight-current-row
          tooltip-effect="dark"
          :row-style="tableRowStyle"
          style="width: 100%"
          @selection-change="handleLeftSelectionChange"
          @row-click="handleLeftClickRow"
        >
          <el-table-column
            type="selection"
            align="center"
            width="28"
          />

          <el-table-column align="center" width="60" prop="id" label="id" />

          <el-table-column width="100" label="Main Image" align="center">
            <template slot-scope="scope">
              <el-tooltip content="Top center" placement="right">
                <img
                  v-if="scope.row.main"
                  class="img-thumbnail"
                  :src="scope.row.main"
                  @click="handleViewImage(scope.row.main)"
                >
                <img
                  v-if="scope.row.main"
                  slot="content"
                  :src="scope.row.main"
                  width="320"
                  @click="handleViewImage(scope.row.main)"
                >
              </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column width="80" label="图片数量" align="center">
            <template slot-scope="scope">
              <span :style="{ color: scope.row.image__count?'black':'red' }">{{ scope.row.image__count }}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="产品信息" show-overflow-tooltip>
            <template slot-scope="scope">
              <span class="mt-truncate" :title="scope.row.name">
                <el-tag v-if="src === 'crawl' && scope.row.category_name">{{ scope.row.category_name }}</el-tag>
                {{ scope.row.name }}</span>
              <span v-if="scope.row.url && scope.row.url.length >0" class="mt-truncate" :title="scope.row.url">
                <hr><a target="_blank" :href="scope.row.url">{{ scope.row.url }}</a></span>

            </template>
          </el-table-column>

          <el-table-column align="center" prop="tag" label="标签" width="180">
            <template slot-scope="scope">
              {{ scope.row.tag.join(',') }}
            </template>
          </el-table-column>

          <el-table-column align="center" prop="category" label="Associated Category" width="141" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.category.join(',') }}
            </template>
          </el-table-column>

          <el-table-column align="center" prop="default_category" label="Default Category" width="120" />

          <el-table-column align="center" label="上传历史" width="70">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.history"
                plain
                icon="el-icon-info"
                size="mini"
                @click="handleShowHistory(scope.row.id)"
              />
            </template>
          </el-table-column>

          <el-table-column align="center" prop="original_price" label="原价" width="100" />

          <el-table-column align="center" label="配置" width="160">
            <template slot-scope="scope">
              <el-dropdown
                split-button
                type="warning"
                size="mini"
                trigger="click"
                @click.stop="handleEditProductAttr(scope.row)"
              >
                模版属性修改
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native.stop="handleSingleUpload(scope.row)">上传单个产品
                  </el-dropdown-item>
                  <el-dropdown-item @click.native.stop="showProductEditFieldsDialog(scope.row, 'single')">产品信息修改
                  </el-dropdown-item>

                  <el-dropdown-item v-if="src === 'crawl'" @click.native.stop="handleDeleteProduct(scope.row)">删除产品
                  </el-dropdown-item>
                </el-dropdown-menu>

              </el-dropdown>

            </template>
          </el-table-column>

        </el-table>
        <el-pagination
          v-if="dataSource.productTableData.length"
          background
          class="mt-pagination"
          :current-page="submitParams.left.page"
          :page-sizes="[20,50,100]"
          :page-size="submitParams.left.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <div class="export-process">
      <span class="mt-span">已选产品</span>
      <div v-if="dataSource.firstStep.tableData.length" class="btn-group">
        <el-button size="mini" type="danger" @click="removeSelectedSelection">移除选中项</el-button>
        <el-button size="mini" @click="clearSelectedSelection">取消选中</el-button>
      </div>
      <el-table
        ref="rightTable"
        v-loading.body="productTableLoading"
        size="mini"
        :data="currentSelectedProducts"
        tooltip-effect="dark"
        border
        fit
        highlight-current-row
        style="width: 100%"
        max-height="810"
        @row-click="handleRightClickRow"
        @selection-change="handleRightSelectionChange"
      >
        <el-table-column
          type="selection"
          align="center"
          width="28"
        />

        <el-table-column align="center" width="60" prop="id" label="id" />

        <el-table-column width="100" label="Main Image" align="center">
          <template slot-scope="scope">
            <el-tooltip content="Top center" placement="right">
              <img
                v-if="scope.row.main"
                class="img-thumbnail"
                :src="scope.row.main"
                @click="handleViewImage(scope.row.main)"
              >
              <img
                v-if="scope.row.main"
                slot="content"
                class="img-thumbnail"
                :src="scope.row.main"
                @click="handleViewImage(scope.row.main)"
              >
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column width="80" label="图片数量" align="center">
          <template slot-scope="scope">
            <span :style="{ color: scope.row.image__count?'black':'red' }">{{ scope.row.image__count }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="名称" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="mt-truncate" :title="scope.row.name">{{ scope.row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="标签" prop="tag" width="180">
          <template slot-scope="scope">
            {{ scope.row.tag.join(',') }}
          </template>
        </el-table-column>

        <el-table-column align="center" prop="category" label="Associated Category" width="141">
          <template slot-scope="scope">
            {{ scope.row.category.join(',') }}
          </template>
        </el-table-column>

        <el-table-column align="center" prop="default_category" label="Default Category" width="120" />

        <el-table-column align="center" label="原价" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.original_price }}</span>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="dataSource.firstStep.tableData.length"
        background
        class="mt-pagination"
        :current-page="selectedProducts.page"
        :page-sizes="[10,50,100]"
        :page-size="selectedProducts.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="dataSource.firstStep.tableData.length"
        @size-change="handleSelectedProductsSizeChange"
        @current-change="handleSelectedProductsPageChange"
      />

      <el-button
        v-if="dataSource.firstStep.tableData.length"
        size="mini"
        type="primary"
        style="margin-left: 40px;margin-top: 20px"
        @click="handleExport"
      >
        {{ process_type==='1'? '导出': '编辑' }}{{ dataSource.firstStep.tableData.length }}件产品
      </el-button>
    </div>

    <div class="export-history">

      <span class="mt-span">上传记录</span>
      <el-table
        v-loading.body="uploadBatchLoading"
        size="mini"
        :data="dataSource.uploadBatch"
        border
        fit
        highlight-current-row
        style="width: 100%; margin-top: 28px;"
      >

        <el-table-column align="center" label="站点信息" width="280">
          <template slot-scope="scope">
            <span>{{ scope.row.website__domain }} | {{ scope.row.website__code }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="状态" prop="state" show-overflow-tooltip width="120">
          <template slot-scope="scope">
            <el-tag :type="scope.row.state | stateFilter">{{ scope.row.state }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="上传时间" prop="create_at" width="160" />

        <el-table-column align="center" label="产品来源" width="70">
          <template slot-scope="scope">
            <span>{{ SRC_MAPPER[scope.row.src] }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="描述" prop="description" show-overflow-tooltip />

      </el-table>
      <el-pagination
        v-if="dataSource.uploadBatch.length"
        background
        class="mt-pagination"
        :current-page="submitParams.upload.page"
        :page-sizes="[20,50,100]"
        :page-size="submitParams.upload.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="batchTotal"
        @size-change="handleUploadBatchSizeChange"
        @current-change="handleUploadBatchPageChange"
      />
    </div>

    <product-attr
      :model="dataSource.productAttrForm"
      :src="src"
      :product_id="dataSource.currentProductId"
      :template-dialog-visible="dataSource.productAttrDialogVisible"
      @reload="getProducts"
      @cancelProductAttrDialog="cancelProductAttrDialog($event)"
    />

    <el-dialog
      :title="dataSource.productDialogTitle"
      :visible.sync="dataSource.editProductDialogVisible"
      width="740px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="editProduct"
    >
      <el-form :model="dataSource.tempProduct" label-position="left" label-width="220px">
        <el-form-item label="标签(使用,间隔)">
          <el-checkbox v-model="dataSource.tempProduct.bool_tag" title="是否修改标签" />
          <el-input v-model="dataSource.tempProduct.tag" />
        </el-form-item>

        <el-form-item label="价格">
          <el-checkbox v-model="dataSource.tempProduct.bool_original_price" title="是否修改价格" />
          <el-input v-model="dataSource.tempProduct.original_price" type="number" />
        </el-form-item>

        <el-form-item label="Name of Associated Category">
          <el-checkbox v-model="dataSource.tempProduct.bool_category" title="是否修改 Name of Associated Category" />
          <el-input
            v-model="filterText"
            placeholder="输入关键字进行过滤"
            size="mini"
            style="padding:10px"
            clearable
          />
          <el-tree
            ref="editProductTree"
            :data="dataSource.fourthStep.catalogs"
            show-checkbox
            node-key="id"
            :default-expanded-keys="dataSource.fourthStep.catalogs.length?[dataSource.fourthStep.catalogs[0].id]:[]"
            :default-checked-keys="defaultCheckedKeys"
            :filter-node-method="filterCategoryNode"
            :expand-on-click-node="false"
            :props="{ children: 'children', label: 'name' }"
            check-strictly
            @check-change="()=>{this.dataSource.tempProduct.category=this.$refs.editProductTree.getCheckedNodes()}"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>{{ data.id + ' | ' + node.label }}</span>
              <span><el-button
                v-if="data.children.length"
                type="text"
                size="mini"
                style="margin-right: 20px"
                @click="showAddCategoryDialog(data)"
              >添加</el-button></span>
            </span>
          </el-tree>
          <el-button
            plain
            icon="el-icon-refresh"
            title="刷新"
            size="mini"
            @click="handleFetchWebsiteCatalogs"
          />
        </el-form-item>

        <el-form-item label="Default Category">
          <el-checkbox v-model="dataSource.tempProduct.bool_default_category" title="是否修改 Default Category" />
          <el-select
            v-model="dataSource.tempProduct.default_category"
            filterable
            clearable
            class="mt-supplier-code-input"
            placeholder="请选择默认目录"
          >
            <el-option
              v-for="item in dataSource.tempProduct.category"
              :key="item.id"
              :label="item.id + ' |  ' + item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dataSource.editProductDialogVisible = false">取 消</el-button>
        <el-button
          v-loading.fullscreen.lock="editAttrFullscreenLoading"
          type="primary"
          @click="handleSubmitEditProductFields"
        >确 定</el-button>
      </span>

      <el-dialog
        v-loading.fullscreen.lock="addCategoryLoading"
        title="添加目录"
        :visible.sync="addCategoryDialogVisible"
        width="80%"
        append-to-body
        label-position="right"
        class="mt-add-category-dialog"
      >
        <el-form :model="submitParams.addCategory" label-position="left" label-width="140px">
          <el-form-item label="* Name">
            <el-input v-model="submitParams.addCategory.name" />
          </el-form-item>

          <el-form-item label="Displayed">
            <el-switch
              v-model="submitParams.addCategory.active"
              active-color="#13ce66"
              active-value="1"
              inactive-value="0"
              inactive-color="#ff4949"
            />
          </el-form-item>

          <br>
          <el-form-item label="Description">
            <tinymce ref="mt_export" v-model="submitParams.addCategory.description" :height="300" />
          </el-form-item>

          <el-form-item label="Meta title">
            <el-input v-model="submitParams.addCategory.meta_title" />
          </el-form-item>

          <el-form-item label="Meta description">
            <el-input v-model="submitParams.addCategory.meta_description" />
          </el-form-item>

          <el-form-item label="Meta keywords">
            <el-input v-model="submitParams.addCategory.meta_keywords" />
          </el-form-item>

          <el-form-item label="* Friendly URL">
            <el-input v-model="submitParams.addCategory.friendly_url" />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addCategoryDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleAddCategory">确 定</el-button>
        </span>
      </el-dialog>

    </el-dialog>

    <export-component
      :website="dataSource.selected_website"
      :source="src"
      :ids="dataSource.ids"
      :process_type="process_type"
      :single_row="single_row"
      :export-dialog-visible="dataSource.exportDialogVisible"
      @reload="fetchUploadBatch"
      @cancelExportDialog="cancelExportDialog($event)"
    />
  </div>
</template>

<script>
import { Get as getSupplier } from '@/api/erp/elicink/supplier'
import { Get as GetCatalog } from '@/api/erp/elicink/catalog'
import {
  dt as dt_from_local,
  Put as put_product_from_local
} from '@/api/erp/elicink/product'
import {
  put_product_from_crawl,
  crawl_product_dt as dt_from_crawl,
  fetch_entity_category,
  delete_task
} from '@/api/erp/crawlproduct'
import {
  showUploadHistory,
  showUploadBatch
} from '@/api/erp/elicink/export_history'
import {
  Get as GetWebsite,
  CatalogTree as GetWebsiteCatalogs,
  AssociationTree as GetAssociations,
  AddCategory
} from '@/api/erp/elicink/website'

import productAttr from './elements/productAttr'
import exportComponent from './elements/exportComponent'

import qs from 'qs'

const _ = require('lodash')
import Tinymce from '@/components/Tinymce'

const SRC_MAPPER = {
  1: '本地',
  2: '抓取'
}
export default {
  name: 'ProductExport',
  components: { exportComponent, productAttr, Tinymce },
  filters: {
    stateFilter(v) {
      switch (v) {
        case 'pending':
          return 'primary'
        case 'success':
          return 'success'
        case 'failed':
          return 'danger'
      }
    }
  },
  data() {
    return {
      filterText: '',
      existed_associated_category_ids: [],
      defaultCheckedKeys: [],
      addCategoryLoading: false,
      addCategoryDialogVisible: false, // 添加目录 dialog 可见

      base_api: '',
      searchAvailable: false, // 搜索禁用
      supplierLoading: true, // 供应商加载
      catalogAvailable: true, // true 目录禁用
      catalogLoading: false, // true 目录加载
      crawl_category_loading: false, // 爬取 目录 加载
      websiteLoading: true, // 站点加载
      templatePreviewDialogVisible: false,

      productTableLoading: false,
      total: 0, // 产品列表总数
      batchTotal: 0, //  上传记录总数
      leftTableCurrentSelection: [], // 上方 当前选择项
      rightTableSelectionRemove: [], // 下方 删除列表格

      exportLoading: false,
      histroyDeleteVisible: false,
      uploadBatchLoading: false,
      editAttrFullscreenLoading: false, // 修改产品属性 全屏loading
      single_row: '', // 单个产品修改的时候数据源
      // 已选产品
      currentSelectedProducts: [],
      selectedProducts: {
        page: 1,
        pagesize: 10
      },
      activeName: 'id',
      dataSource: {
        selected_website: null,
        ids: [],
        // top 选择项的可选项
        suppliers: [],
        catalogs: [],
        websites: [],
        crawl_category_names: [], // 爬取产品的 目录名称选择

        // 产品列表
        productTableData: [],
        // 产品的项目属性
        product__project_attrs: [],

        // 产品列表 修改 属性.
        currentProductId: null,
        // 当前 product row 模版编辑表单内容
        productAttrForm: {},
        // 当前 产品属性 dialogVsible
        productAttrDialogVisible: false,

        // 修改产品的 Dialog
        productDialogTitle: null,
        editProductDialogVisible: false,
        tempProduct: {
          bool_tag: true,
          bool_original_price: true,
          bool_category: true,
          bool_default_category: true,
          tag: '',
          original_price: 0,
          category: [],
          default_category: null,
          batch: 2
        },
        productEditCurrentId: null,

        // 产品导出项
        firstStep: {
          tableData: []
        },
        fourthStep: {
          catalogs: []
        },
        // history
        // exportHistory: [],

        exportDialogVisible: false,

        uploadBatch: []
      },
      submitParams: {
        left: {
          s_id: null,
          c_id: [],
          w_id: null,
          crawl_category_name: null,
          kw: '',
          pagesize: 20,
          page: 1
        },
        upload: {
          pagesize: 20,
          page: 1
        },
        addCategory: {
          name: '',
          active: '1',
          id_parent: null,
          description: '',
          meta_title: '',
          meta_description: '',
          meta_keywords: '',
          friendly_url: ''
        }
      },
      SRC_MAPPER: SRC_MAPPER
    }
  },
  computed: {
    category_name() {
      return this.submitParams.addCategory.name
    },
    src() {
      return this.$route.params.src || 'local'
    },
    process_type() {
      return this.$route.query.process_type || '1'
    }
  },
  watch: {
    filterText(val) {
      this.$refs.editProductTree.filter(val)
    },
    category_name(val) {
      if (val) this.submitParams.addCategory.friendly_url = _.trim(val, '-').split(' ').join('-')
    }
  },
  created() {
    if (this.src === 'local') {
      this.fetchSuppliers()
    }
    this.fetchUploadBatch()
    this.fetchWebsites()
    this.base_api = process.env.VUE_APP_BASE_API
  },
  methods: {
    // 动态类名
    tableRowStyle({ row, rowIndex }) {
      if (row.bool_upload) {
        return 'background-color: oldlace'
      }
      return ''
    },
    // 处理供应商更改
    handleSupplierChange(value) {
      switch (this.src) {
        case 'local':
          this.getCatalogs(null, 's_id=' + value)
          this.submitParams.left.c_id = []
          this.submitParams.left.kw = ''
          break
        case 'crawl':
          return
      }
      this.checkSelections()
    },
    // 左上方 三个选择器必须 都有数据，才能进行产品展示。
    checkSelections() {
      switch (this.src) {
        case 'local':
          this.searchAvailable = Boolean(
            this.submitParams.left.s_id &&
              this.submitParams.left.w_id &&
              this.submitParams.left.c_id.length)
          break
        case 'crawl':
          this.searchAvailable = Boolean(this.submitParams.left.w_id)
      }
    },
    handleWebsiteChange(v) {
      if (v) {
        this.dataSource.fourthStep.catalogs = []
        this.dataSource.selected_website = _.find(this.dataSource.websites, { id: v })
        this.handleFetchWebsiteCatalogs()
        this.checkSelections()

        if (this.src === 'crawl') {
          this.crawl_category_loading = true
          this.submitParams.left.crawl_category_name = null
          fetch_entity_category({ 'w_id': v, 'process_type': this.process_type })
            .then(response => {
              this.dataSource.crawl_category_names = response.data
              this.crawl_category_loading = false
            }).catch(e => { this.crawl_category_loading = false })
        }
      }
    },
    handleFetchWebsiteCatalogs() {
      GetWebsiteCatalogs(this.submitParams.left.w_id).then(respone => {
        this.dataSource.fourthStep.catalogs = respone.data
      })
    },
    fetchAssociations() {
      GetAssociations(this.submitParams.left.w_id).then(response => {
        this.dataSource.thirdStep.associations = response.data
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.submitParams.left.pagesize = val
      this.getProducts()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.submitParams.left.page = val
      this.getProducts()
    },
    // pageSize 改变后触发 table 更新
    handleUploadBatchSizeChange(val) {
      this.submitParams.upload.pagesize = val
      this.fetchUploadBatch()
    },
    // page 改变后触发 table 更新
    handleUploadBatchPageChange(val) {
      this.submitParams.upload.page = val
      this.fetchUploadBatch()
    },
    // 已选产品 pagesize 改变
    handleSelectedProductsSizeChange(val) {
      this.selectedProducts.pagesize = val
      this.getSelectedProducts()
    },
    // 已选产品 page 改变后触发 table 更新
    handleSelectedProductsPageChange(val) {
      this.selectedProducts.page = val
      this.getSelectedProducts()
    },
    // 点击搜索
    handleSearch() {
      this.submitParams.left.page = 1
      this.getProducts()
      this.searchAvailable = false
    },
    // 待选产品（左侧table）中当前已勾选 rows 列表
    handleLeftSelectionChange(val) {
      this.leftTableCurrentSelection = val
    },
    // 添加选中项目到 右侧 table 的数据源中
    addSelection() {
      if (this.leftTableCurrentSelection.length) {
        this.dataSource.firstStep.tableData = _.uniqBy(
          _.concat(this.dataSource.firstStep.tableData, _.cloneDeep(this.leftTableCurrentSelection)),
          'id')
        this.notify('添加成功')
        this.$refs.leftTable.clearSelection()
        this.reloadSelectedTable()
      }
    },
    reloadSelectedTable() {
      this.selectedProducts.page = 1
      this.getSelectedProducts()
    },
    // 清空未选产品（左侧table）的当前勾选项目
    clearSelection() {
      this.$refs.leftTable.clearSelection()
    },
    // 已选产品（右侧table） 中当前已勾选 rows 列表
    handleRightSelectionChange(val) {
      this.rightTableSelectionRemove = val
    },
    removeSelectedSelection() {
      if (this.rightTableSelectionRemove.length) {
        for (const f of this.rightTableSelectionRemove) {
          const tmp_index = _.findIndex(this.dataSource.firstStep.tableData, (m) => m.id === f.id)
          if (tmp_index > -1) {
            this.dataSource.firstStep.tableData.splice(tmp_index, 1)
          }
        }
        this.notify('移除成功')
        this.reloadSelectedTable()
        this.$refs.rightTable.clearSelection()
      }
    },
    // 清空已选产品（右侧table）的当前勾选项目
    clearSelectedSelection() {
      this.$refs.rightTable.clearSelection()
    },
    // 单个产品上传
    handleSingleUpload(row) {
      this.dataSource.ids = [row.id]
      this.single_row = row
      console.log(this.single_row)
      this.dataSource.exportDialogVisible = true
    },
    // 修改 模版属性
    handleEditProductAttr(row) {
      const single = () => {
        this.dataSource.productAttrDialogVisible = true
        if (this.src === 'crawl') {
          console.log(row)
          this.dataSource.productAttrForm = row.attr.length && row.attr || this.dataSource.product__project_attrs
          this.dataSource.currentProductId = row.entity_id
          console.log(this.dataSource.currentProductId)
          console.log(this.dataSource.productAttrForm)
        } else {
          this.dataSource.productAttrForm = row.attr.length && row.attr || this.dataSource.product__project_attrs
          this.dataSource.currentProductId = row.id
        }
      }
      if (Array.isArray(row)) {
        if (row.length === 1) {
          row = row[0]
          single()
          return
        }
        this.dataSource.productAttrDialogVisible = true
        // this.dataSource.productAttrForm = this.src === 'crawl' ? this.dataSource.selected_website.attr : this.dataSource.product__project_attrs
        this.dataSource.productAttrForm = this.dataSource.product__project_attrs
        this.dataSource.currentProductId = this.src === 'crawl' ? row.map(v => v.entity_id) : row.map(v => v.id)
      } else {
        single()
      }
    },
    // 获取供应商
    fetchSuppliers() {
      getSupplier().then(response => {
        this.dataSource.suppliers = response.data.data
        this.supplierLoading = false
      }).catch(e => {
        this.supplierLoading = false
      })
    },
    // 获取站点
    fetchWebsites() {
      GetWebsite().then(response => {
        this.dataSource.websites = response.data.data
        this.websiteLoading = false
      }).catch(e => {
        this.websiteLoading = false
      })
    },
    // 获取目录
    getCatalogs(id, args) {
      this.catalogLoading = true
      GetCatalog(id, args).then(response => {
        this.catalogAvailable = true
        this.dataSource.catalogs = response.data.data
        if (this.dataSource.catalogs.length === 1) {
          this.submitParams.left.c_id = [this.dataSource.catalogs[0].id]
          this.checkSelections()
        }
        this.catalogAvailable = response.data.data.length < 0
        this.catalogLoading = false
      }).catch(e => {
        this.catalogLoading = false
      })
    },
    // 获取所有产品
    getProducts(foo, reload) {
      this.productTableLoading = true
      const dt_method = this.src === 'local' ? dt_from_local : dt_from_crawl
      const vars = Object.assign({}, this.submitParams.left, { process_type: this.process_type })

      dt_method(qs.stringify(vars, { arrayFormat: 'repeat' })).then(response => {
        this.dataSource.product__project_attrs = response.project__attr || []
        this.dataSource.productTableData = response.data.data
        if (foo instanceof Function) {
          foo()
        }
        if (reload instanceof Function) {
          reload()
        }
        this.productTableLoading = false
        this.total = response.data.total
        this.searchAvailable = true
      }).catch(e => {
        this.productTableLoading = false
        this.searchAvailable = true
      })
    },
    getSelectedProducts() {
      const page = this.selectedProducts.page
      const size = this.selectedProducts.pagesize
      this.currentSelectedProducts = _.cloneDeep(this.dataSource.firstStep.tableData).slice((page - 1) * size, page * size)
    },
    fetchUploadBatch() {
      this.uploadBatchLoading = true
      showUploadBatch(null, qs.stringify(this.submitParams.upload, { arrayFormat: 'repeat' })).then(response => {
        this.dataSource.uploadBatch = response.data.data
        this.batchTotal = response.data.total
        this.uploadBatchLoading = false
      }).catch(e => {
        this.uploadBatchLoading = false
      })
    },
    // productAttr form dialog 隐藏
    cancelProductAttrDialog(v) {
      this.dataSource.productAttrDialogVisible = v
    },
    notify(message, duration, type) {
      this.$notify({
        title: '成功',
        message: message,
        type: type || 'success',
        duration: duration || 2000
      })
    },
    handleViewImage(v) {
      window.open(v)
    },
    showText(type, id) {
      let text
      switch (type) {
        case 'title':
          text = _.find(this.dataSource.secondStep.titleTemplates, { id: id }).text
          break
        case 'keyword':
          text = _.find(this.dataSource.secondStep.keywordTemplates, { id: id }).text
          break
        case 'desc':
          text = _.find(this.dataSource.secondStep.descTemplates, { id: id }).text
          break
        case 'longDesc':
          text = _.find(this.dataSource.secondStep.longDescTemplates, { id: id }).text
          break
      }
      this.$alert(text, '内容', {
        dangerouslyUseHTMLString: true
      })
    },
    filterMethod(query, item) {
      return item.name.indexOf(query) > -1
    },
    handleSubmitEditProductFields() {
      this.editAttrFullscreenLoading = true
      let ajax_method
      switch (this.src) {
        case 'local':
          ajax_method = put_product_from_local
          break
        case 'crawl':
          ajax_method = put_product_from_crawl
          break
      }
      const src = this.src
      if (this.dataSource.productEditCurrentId instanceof Array) {
        const pks = this.dataSource.productEditCurrentId
        this.dataSource.tempProduct.ids = pks
        ajax_method(null,
          Object.assign({}, this.dataSource.tempProduct, {
            category: this.dataSource.tempProduct.category.map(m => m.id).join(',')
          }))
          .then(response => {
            this.dataSource.editProductDialogVisible = false
            this.getProducts(() => {
              pks.map(pk => {
                const _index = _.findIndex(this.dataSource.firstStep.tableData, (o) => {
                  if (src === 'local') {
                    return o.id === pk
                  } else {
                    return o.entity_id === pk
                  }
                })
                if (_index > -1) {
                  const _id = this.dataSource.firstStep.tableData[_index].id

                  const new_index = _.findIndex(this.dataSource.productTableData, o => o.id === _id)
                  if (new_index > -1) {
                    this.dataSource.firstStep.tableData.splice(_index, 1, this.dataSource.productTableData[new_index])
                  }
                }
              })
            }, this.reloadSelectedTable)
            this.editAttrFullscreenLoading = false
          }
          ).catch((e) => {
          })
      } else {
        ajax_method(this.dataSource.productEditCurrentId,
          Object.assign({}, this.dataSource.tempProduct, {
            category: this.dataSource.tempProduct.category.map(m => m.id).join(',')
          })
        )
          .then(response => {
            this.dataSource.editProductDialogVisible = false
            this.getProducts(() => {
              const _index = _.findIndex(this.dataSource.firstStep.tableData,
                (o) => {
                  if (src === 'local') {
                    return o.id === this.dataSource.productEditCurrentId
                  } else {
                    return o.entity_id === this.dataSource.productEditCurrentId
                  }
                })
              if (_index > -1) {
                const _id = this.dataSource.firstStep.tableData[_index].id

                const new_index = _.findIndex(this.dataSource.productTableData, o => o.id === _id)
                if (new_index > -1) {
                  this.dataSource.firstStep.tableData.splice(_index, 1, this.dataSource.productTableData[new_index])
                }
              }
            }, this.reloadSelectedTable)
            this.editAttrFullscreenLoading = false
          }).catch(() => {
          })
      }
    },
    resetTempProduct() {
      this.dataSource.tempProduct = {
        bool_tag: true,
        bool_original_price: true,
        bool_category: true,
        bool_default_category: true,
        tag: '',
        original_price: 0,
        category: [],
        batch: 2,
        default_category: null
      }
      this.dataSource.productEditCurrentId = null
      this.defaultCheckedKeys = []
    },
    showProductEditFieldsDialog(field_or_fileds, type) {
      this.defaultCheckedKeys = []
      const single = () => {
        this.dataSource.productDialogTitle = '单个修改产品信息'
        this.dataSource.productEditCurrentId = this.src === 'local' ? field_or_fileds.id : field_or_fileds.entity_id
        this.dataSource.tempProduct = {
          batch: 1,
          bool_tag: true,
          bool_original_price: true,
          bool_category: true,
          bool_default_category: true,
          tag: field_or_fileds.tag.join(','),
          original_price: field_or_fileds.original_price,
          category: field_or_fileds.category,
          default_category: field_or_fileds.default_category
        }
        this.dataSource.editProductDialogVisible = true
        this.$nextTick(() => {
          this.defaultCheckedKeys = field_or_fileds.category.map(m => parseInt(m))
          this.$refs.editProductTree.setCheckedKeys(this.defaultCheckedKeys) // 设置默认的 Id of Associated categories
          this.dataSource.tempProduct.category = this.$refs.editProductTree.getCheckedNodes()
        })
      }
      switch (type) {
        case 'single': {
          single()
          break
        }
        case 'multi': {
          if (field_or_fileds.length === 1) {
            field_or_fileds = field_or_fileds[0]
            single()
            break
          }
          this.resetTempProduct()
          this.$nextTick(() => {
            this.$refs.editProductTree.setCheckedKeys(this.defaultCheckedKeys) // 设置默认的 Id of Associated categories
            this.dataSource.tempProduct.category = this.$refs.editProductTree.getCheckedNodes()
          })
          this.dataSource.productDialogTitle = '批量修改产品信息'
          this.dataSource.productEditCurrentId = this.src === 'local' ? field_or_fileds.map(v => v.id) : field_or_fileds.map(v => v.entity_id)
          this.dataSource.editProductDialogVisible = true
          break
        }
      }
    },
    handleExport() {
      this.dataSource.ids = this.dataSource.firstStep.tableData.map(m => m.id)
      this.dataSource.exportDialogVisible = true
    },
    cancelExportDialog(v) {
      this.dataSource.ids = []
      this.dataSource.exportDialogVisible = false
    },
    handleShowHistory(id) {
      this.productTableLoading = true
      showUploadHistory(qs.stringify({
        id: id,
        src: this.src,
        w_id: this.submitParams.left.w_id
      }, { arrayFormat: 'repeat' }))
        .then(response => {
          this.productTableLoading = false
          this.$alert(response.data.data, '上传历史', {
            dangerouslyUseHTMLString: true,
            customClass: 'mt-alert'
          })
        })
        .catch(e => {
          this.productTableLoading = false
        })
    },
    handleLeftClickRow(row) {
      this.$refs.leftTable.toggleRowSelection(row)
    },
    handleRightClickRow(row) {
      this.$refs.rightTable.toggleRowSelection(row)
    },
    showAddCategoryDialog(data) {
      this.submitParams.addCategory = {
        name: '',
        active: '1',
        id_parent: data.id,
        description: '',
        meta_title: '',
        meta_description: '',
        meta_keywords: '',
        friendly_url: ''
      }

      this.$nextTick(() => {
        this.$refs.mt_export.destroyTinymce()
        this.$refs.mt_export.initTinymce()
        this.$refs.mt_export.setContent('')
      })
      this.addCategoryDialogVisible = true
    },
    handleAddCategory() {
      this.addCategoryLoading = true
      AddCategory(Object.assign(this.submitParams.addCategory,
        { website_id: this.submitParams.left.w_id }))
        .then(response => {
          this.addCategoryLoading = false
          this.addCategoryDialogVisible = false
          this.handleFetchWebsiteCatalogs()
        })
        .catch(e => {
          this.addCategoryLoading = false
        })
    },
    filterCategoryNode(value, data) {
      if (!value) return true
      return data.name.toLocaleLowerCase().indexOf(value.toLocaleLowerCase()) !== -1
    },
    addTotal() {
      // 添加全部.
    },
    handleDeleteProduct(row) {
      if (row) {
        delete_task(row.id).then(response => {
          this.notify('删除成功')
          this.handleSearch()
        }).catch(e => {
          this.notify('删除失败', null, 'danger')
        })
      } else {
        const vars = Object.assign({}, this.submitParams.left, { process_type: this.process_type })
        delete_task(null, JSON.stringify(vars, { arrayFormat: 'repeat' })).then(response => {
          this.notify('删除成功')
          this.handleSearch()
        }).catch(e => {
          this.notify('删除失败', null, 'danger')
        })
      }
    }
  }
}
</script>

<style scoped>
  #line {
    height: 1px;
    background-color: #d3d3d3;
    display: inline-block;
    width: 100%;
    margin-top: 15px;
    margin-bottom: 20px;
  }

  .mt-span {
    font-family: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑",
    Arial, sans-serif;
    padding-top: 10px;
    padding-left: 5px;
  }

  .mt-form-item-left {
    width: 30%;
    margin-right: 0;
  }

  .mt-form-item-left >>> .el-select {
    width: 100%;
  }

  .mt-form-item-left >>> .el-form-item__content {
    width: calc(100% - 55px);
  }

  .mt-form-item-center {
    width: 36%;
    margin-right: 0;
  }

  .mt-form-item-center >>> .el-form-item__content {
    width: calc(100% - 41px);
  }

  .mt-form-item-center >>> .el-select {
    width: 100%;
  }

  .mt-form-item-right {
    width: 32%;
    margin-right: 0;
  }

  .mt-form-item-right >>> .el-form-item__content {
    width: calc(100% - 41px);
  }

  .mt-form-item-right >>> .el-select {
    width: 100%;
  }

  .app-container {
    position: relative;
    height: 88.5vh;
    padding: 0px;
  }

  .top-two-panel {
    width: 98%;
    padding: 16px 16px 46px 16px;
    background: rgb(255, 255, 255);
  }

  .btn-group {
    float: right;
    margin-bottom: 20px;
  }

  .export-process {
    overflow: auto;
    width: 98%;
    /*height: calc(100% - 45px);*/
    background: rgb(255, 255, 255);
    padding: 16px 16px 46px 16px;
    margin: 15px;
    position: relative;
  }

  .export-history {
    width: 98%;
    height: 100%;
    padding: 30px;
    margin: 15px;
    background: rgb(255, 255, 255);
    overflow-y: scroll;
  }

  .demo-form-inline {
    margin-top: 20px;
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .mt-supplier-code-input {
    width: 80%;
  }

  .app-container >>> span.el-tag--info {
    word-break: normal;
    width: auto;
    display: block;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow: hidden;
  }

  .mt-truncate {
    width: 100px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .el-table td, .el-table th {
      padding: 1px 0;
  }

  .export-history a {
    text-decoration: underline red;
  }

  .export-history::-webkit-scrollbar { /*滚动条整体样式*/
    width: 10px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
  }

  .export-history::-webkit-scrollbar-thumb { /*滚动条里面小方块*/
    border-radius: 10px;
    background-color: #F90;
    background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .2) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 75%, transparent 75%, transparent);
  }

  .export-history::-webkit-scrollbar-track { /*滚动条里面轨道*/
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    /*border-radius: 10px;*/
    background: #EDEDED;
  }

  .editProduct >>> .el-input {
    display: inline-block;
    width: 400px
  }

  .mt-export-dialog >>> .el-transfer-panel {
    width: calc(50% - 60px);
  }

  .mt-export-dialog >>> .el-dialog {
    margin-top: 28px !important;
    margin-bottom: 68px;
  }

  .mt-export-dialog >>> .el-dialog__body {
    padding-top: 0;
  }

  .mt-export-dialog >>> .el-tabs__content {
    overflow-y: scroll;
    height: 680px;
  }

  .mt-export-dialog >>> .el-tabs__content::-webkit-scrollbar { /*滚动条整体样式*/
    width: 10px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
  }

  .mt-export-dialog >>> .el-tabs__content::-webkit-scrollbar-thumb { /*滚动条里面小方块*/
    border-radius: 10px;
    background-color: #909399;
    background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .2) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 75%, transparent 75%, transparent);
  }

  .mt-export-dialog >>> .el-tabs__content::-webkit-scrollbar-track { /*滚动条里面轨道*/
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    /*border-radius: 10px;*/
    background: #EDEDED;
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .mt-add-category-dialog >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 48px;
  }

  .app-container >>> .img-thumbnail {
    width: 30px;
    height: auto;
  }
</style>
